package com.dongzili.postgresql.common.mybatisplus.postgresql;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.OffsetDateTime;

/**
 * 将数据库TIMESTAMPTZ类型转换为Java LocalDate
 */
public class TimestampTzToLocalDateConverter extends BaseTypeHandler<LocalDate> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType) throws SQLException {
        // 写入数据库时：LocalDate -> OffsetDateTime（带默认时区）
        ps.setObject(i, OffsetDateTime.of(parameter.atStartOfDay(), OffsetDateTime.now().getOffset()));
    }

    @Override
    public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从数据库读取时：TIMESTAMPTZ -> OffsetDateTime -> LocalDate
        OffsetDateTime odt = rs.getObject(columnName, OffsetDateTime.class);
        return odt != null ? odt.toLocalDate() : null;
    }

    @Override
    public LocalDate getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        OffsetDateTime odt = rs.getObject(columnIndex, OffsetDateTime.class);
        return odt != null ? odt.toLocalDate() : null;
    }

    @Override
    public LocalDate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        OffsetDateTime odt = cs.getObject(columnIndex, OffsetDateTime.class);
        return odt != null ? odt.toLocalDate() : null;
    }
}
    